% generate_trials_postitions_auto
% By using a continous signal and knowing how many movements were performed
% this function will detect the signal that corresponds only to he
% movements. It is a brute force optimization task (with constraints)

function [best_index best_trigger] = generate_trials_postitions_auto(dataf)

last_size = 200;
best_trigger = [];
best_index = [];
length =  size(dataf,2);
    
for scale = 1.2:0.2:2.5
    %for scale = 1.5:0.1:3.0
       
        %calculate power
%         ms = dataf(:,1);
%         %power  = (conv(ms'.^2,rectwin(1000)));
%         
%         power = Deriche.FirstDeriv(ms', alpha);
%         power(power<0)=0;
%         power = conv(power,rectwin(1000));
%         
%         trigger = power > scale * median(power);
%         best_index = find(diff(trigger)==1);
%         last_size = size(best_index,2);

        for ich = 1:length 
            ms = dataf(:,ich);
            %power  = (conv(sum(data'.^2),rectwin(1000)));
            power  = (conv(ms'.^2,rectwin(1000)));
            
%             power = Deriche.FirstDeriv(ms', alpha);
%             power(power<0)=0;
%             power = conv(power,rectwin(1000));
            
            % the period of interest are 4 times greater than the median (just a guess)
            trigger = power > scale * median(power);
            if (sum(trigger) == 0) 
                continue; 
            end;
                
            % check for unrealisticly small or high events
            counts = count_sequence(trigger);
            msl1 = 200;%into samples
            msl2 = 4000;%into samples
            if (min(counts) < msl1|| max(counts) > msl2)
                continue;
            end;
            
            current_index = find(diff(trigger)==1);
            
            %last_size = size(index,2);
         
            cuurent_size = size(current_index,2);
            %disp([int2str(cuurent_size) ' ' num2str(scale) ' ' num2str(last_size)]);
            
            if (~isempty(current_index) && (abs(cuurent_size-20) < abs(last_size-20)) )
                best_index = current_index;
                last_size = cuurent_size;
                best_trigger = trigger;
                disp('new optimization solution found');
                %min(counts) % should be related to window?
            end
            
            %if (abs(size(temp_index,2)-20) == abs(last_size-20)) disp('dup'); end;
        end;
    end;




